local header = [[
..\Base.simc

report_details=0

name=NoTrinket
trinket1=
trinket2=

gear_expertise_rating=2551
gear_hit_rating=2551

default_actions=1
]]

local base_profiles = {
	{ "Death_Knight_Frost_1h_T16H",		"Str",	"mastery",	"死亡骑士 - 冰霜 - 双持",	},
	{ "Death_Knight_Frost_2h_T16H",		"Str",	"haste",	"死亡骑士 - 冰霜 - 双手",	},
	{ "Death_Knight_Unholy_T16H",		"Str",	"crit",		"死亡骑士 - 邪恶",			},
	{ "Druid_Balance_T16H",				"Int",	"crit",		"德鲁伊 - 平衡",			},
	{ "Druid_Feral_T16H",				"Agi",	"mastery",	"德鲁伊 - 野性",			},
	{ "Hunter_BM_T16H",					"Agi",	"crit",		"猎人 - 野兽控制",			},
	{ "Hunter_MM_T16H",					"Agi",	"haste",	"猎人 - 射击",			},
	{ "Hunter_SV_T16H",					"Agi",	"crit",		"猎人 - 生存",			},
	{ "Mage_Arcane_T16H",				"Int",	"mastery",	"法师 - 奥术",			},
	{ "Mage_Fire_T16H",					"Int",	"crit",		"法师 - 火焰",			},
	{ "Mage_Frost_T16H",				"Int",	"haste",	"法师 - 冰霜",			},
	{ "Monk_Windwalker_1h_T16H",		"Agi",	"crit",		"武僧 - 踏风 - 双持",		},
	{ "Monk_Windwalker_2h_T16H",		"Agi",	"crit",		"武僧 - 踏风 - 双手",		},
	{ "Paladin_Retribution_T16H",		"Str",	"haste",	"圣骑士 - 惩戒",			},
	{ "Priest_Shadow_T16H",				"Int",	"haste",	"牧师 - 暗影",			},
	{ "Rogue_Assassination_T16H",		"Agi",	"haste",	"潜行者 - 刺杀",			},
	{ "Rogue_Combat_T16H",				"Agi",	"haste",	"潜行者 - 战斗",			},
	{ "Rogue_Subtlety_T16H",			"Agi",	"haste",	"潜行者 - 敏锐",			},
	{ "Shaman_Elemental_T16H",			"Int",	"mastery",	"萨满祭司 - 元素",			},
	{ "Shaman_Enhancement_T16H",		"Agi",	"mastery",	"萨满祭司 - 增强",			},
	{ "Warlock_Affliction_T16H",		"Int",	"mastery",	"术士 - 痛苦",			},
	{ "Warlock_Demonology_T16H",		"Int",	"haste",	"术士 - 恶魔学识",			},
	{ "Warlock_Destruction_T16H",		"Int",	"mastery",	"术士 - 毁灭",			},
	{ "Warrior_Arms_T16H",				"Str",	"crit",		"战士 - 武器",			},
	{ "Warrior_Fury_1h_T16H",			"Str",	"crit",		"战士 - 狂怒 - 双持",		},
	{ "Warrior_Fury_2h_T16H",			"Str",	"crit",		"战士 - 狂怒 - 双手",		},
}

local Trinkets = {
	Agi = {
		{ name = "既定之天命",	token = "assurance_of_consequence",
			varies = {
				{ id = 104974, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104725, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102292, suffix = "N",	ilvl = 553, },
				{ id = 105223, suffix = "WF",	ilvl = 559, },
				{ id = 104476, suffix = "H",	ilvl = 566, },
				{ id = 105472, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "哈洛姆的护符",	token = "haromms_talisman",
			varies = {
				{ id = 105029, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104780, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102301, suffix = "N",	ilvl = 553, },
				{ id = 105278, suffix = "WF",	ilvl = 559, },
				{ id = 104531, suffix = "H",	ilvl = 566, },
				{ id = 105527, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "暴怒之印",	token = "sigil_of_rampage",
			varies = {
				{ id = 105082, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104833, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102302, suffix = "N",	ilvl = 553, },
				{ id = 105331, suffix = "WF",	ilvl = 559, },
				{ id = 104584, suffix = "H",	ilvl = 566, },
				{ id = 105580, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "滴答作响的黑色雷管",	token = "ticking_ebon_detonator",	constantStat = "mastery",
			varies = {
				{ id = 105114, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104865, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102311, suffix = "N",	ilvl = 553, },
				{ id = 105363, suffix = "WF",	ilvl = 559, },
				{ id = 104616, suffix = "H",	ilvl = 566, },
				{ id = 105612, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "雪怒之律",	token = "discipline_of_xuen",
			varies = {
				{ id = 103986, suffix = "U",	ilvl = 535, maxupgrade = 2, },
				{ id = 103686, suffix = "N",	ilvl = 496, maxupgrade = 2, },
			},
		},
		{ name = "飞箭奖章",	token = "arrowflight_medallion",
			varies = {
				{ id = 93258, suffix = "",	ilvl = 496, maxupgrade = 2, },
			},
		},
		{ name = "雷纳塔基的灵魂符咒",	token = "renatakis_soul_charm", constantStat = "exp",
			varies = {
				{ id = 95625, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94512, suffix = "N",		ilvl = 522, },
				{ id = 95997, suffix = "TF",	ilvl = 528, },
				{ id = 96369, suffix = "H",		ilvl = 535, },
				{ id = 96741, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "邪恶魂能",	token = "bad_juju",	constantStat = "mastery",
			varies = {
				{ id = 95665, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94523, suffix = "N",		ilvl = 522, },
				{ id = 96037, suffix = "TF",	ilvl = 528, },
				{ id = 96409, suffix = "H",		ilvl = 535, },
				{ id = 96781, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "杀戮护符",	token = "talisman_of_bloodlust",
			varies = {
				{ id = 95748, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94522, suffix = "N",		ilvl = 522, },
				{ id = 96120, suffix = "TF",	ilvl = 528, },
				{ id = 96492, suffix = "H",		ilvl = 535, },
				{ id = 96864, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "重生符文",	token = "rune_of_reorigination",
			varies = {
				{ id = 95802, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94532, suffix = "N",		ilvl = 522, },
				{ id = 96174, suffix = "TF",	ilvl = 528, },
				{ id = 96546, suffix = "H",		ilvl = 535, },
				{ id = 96918, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "影踪突袭营的邪恶护符",	token = "vicious_talisman_of_the_shadopan_assault",	constantStat = "hit",
			varies = {
				{ id = 94511, suffix = "",		ilvl = 522, maxupgrade = 2, },
			},
		},
	},

	Str = {
		{ name = "融火之核",	token = "fusionfire_core",
			varies = {
				{ id = 104961, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104712, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102295, suffix = "N",	ilvl = 553, },
				{ id = 105210, suffix = "WF",	ilvl = 559, },
				{ id = 104463, suffix = "H",	ilvl = 566, },
				{ id = 105459, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "迦拉卡斯的邪恶之眼",	token = "evil_eye_of_galakras",
			varies = {
				{ id = 104993, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104744, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102298, suffix = "N",	ilvl = 553, },
				{ id = 105242, suffix = "WF",	ilvl = 559, },
				{ id = 104495, suffix = "H",	ilvl = 566, },
				{ id = 105491, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "斯基尔的沁血护符",	token = "skeers_bloodsoaked_talisman",
			varies = {
				{ id = 105134, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104885, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102308, suffix = "N",	ilvl = 553, },
				{ id = 105383, suffix = "WF",	ilvl = 559, },
				{ id = 104636, suffix = "H",	ilvl = 566, },
				{ id = 105632, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "索克的尾巴尖",	token = "thoks_tail_tip",
			varies = {
				{ id = 105111, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104862, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102305, suffix = "N",	ilvl = 553, },
				{ id = 105360, suffix = "WF",	ilvl = 559, },
				{ id = 104613, suffix = "H",	ilvl = 566, },
				{ id = 105609, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "雪怒之捷",	token = "alacrity_of_xuen",
			varies = {
				{ id = 103989, suffix = "U",	ilvl = 535, maxupgrade = 2, },
				-- { id = , suffix = "N",	ilvl = 496, maxupgrade = 2, },
			},
		},
		{ name = "季鹍的传说之羽",	token = "fabled_feather_of_jikun",	constantStat = "hit",
			varies = {
				-- { id = , suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94515, suffix = "N",		ilvl = 522, },
				{ id = 96098, suffix = "TF",	ilvl = 528, },
				{ id = 96470, suffix = "H",		ilvl = 535, },
				{ id = 96842, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "普利莫修斯的狂怒护符",	token = "primordius_talisman_of_rage",	constantStat = "crit",
			varies = {
				-- { id = , suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94519, suffix = "N",		ilvl = 522, },
				{ id = 96129, suffix = "TF",	ilvl = 528, },
				{ id = 96501, suffix = "H",		ilvl = 535, },
				{ id = 96873, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "赞达拉之火",	token = "spark_of_zandalar",
			varies = {
				-- { id = , suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94526, suffix = "N",		ilvl = 522, },
				{ id = 96026, suffix = "TF",	ilvl = 528, },
				{ id = 96398, suffix = "H",		ilvl = 535, },
				{ id = 96770, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "双后的凝视",	token = "gaze_of_the_twins",
			varies = {
				-- { id = , suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94529, suffix = "N",		ilvl = 522, },
				{ id = 96171, suffix = "TF",	ilvl = 528, },
				{ id = 96543, suffix = "H",		ilvl = 535, },
				{ id = 96915, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "影踪突袭营的野蛮护符",	token = "brutal_talisman_of_the_shadopan_assault",	constantStat = "exp",
			varies = {
				{ id = 94508, suffix = "",		ilvl = 522, maxupgrade = 2, },
			},
		},
	},

	Int = {
		{ name = "亚煞极的黑暗之血",	token = "Black Blood of Y'Shaarj",	constantStat = "haste",
			varies = {
				{ id = 105150, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104901, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102310, suffix = "N",	ilvl = 553, },
				{ id = 105399, suffix = "WF",	ilvl = 559, },
				{ id = 104652, suffix = "H",	ilvl = 566, },
				{ id = 105648, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "伊墨苏斯的净化之缚",	token = "Purified Bindings of Immerseus",
			varies = {
				{ id = 104924, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104675, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102293, suffix = "N",	ilvl = 553, },
				{ id = 105173, suffix = "WF",	ilvl = 559, },
				{ id = 104426, suffix = "H",	ilvl = 566, },
				{ id = 105422, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "卡德里斯的剧毒图腾",	token = "Kardris' Toxic Totem",
			varies = {
				{ id = 105042, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104793, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102300, suffix = "N",	ilvl = 553, },
				{ id = 105291, suffix = "WF",	ilvl = 559, },
				{ id = 104544, suffix = "H",	ilvl = 566, },
				{ id = 105540, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "狂怒水晶",	token = "Frenzied Crystal of Rage",
			varies = {
				{ id = 105074, suffix = "LFR",	ilvl = 528, maxupgrade = 2, },
				{ id = 104825, suffix = "Flex",	ilvl = 540, maxupgrade = 2, },
				{ id = 102303, suffix = "N",	ilvl = 553, },
				{ id = 105323, suffix = "WF",	ilvl = 559, },
				{ id = 104576, suffix = "H",	ilvl = 566, },
				{ id = 105572, suffix = "HWF",	ilvl = 572, },
			},
		},
		{ name = "玉珑之噬",	token = "Yu'lon's Bite",
			varies = {
				{ id = 103987, suffix = "U",	ilvl = 535, maxupgrade = 2, },
				-- { id = 103689, suffix = "N",	ilvl = 496, maxupgrade = 2, },
			},
		},
		{ name = "乌苏雷的最终抉择",	token = "Wushoolay's Final Choice",	constantStat = "hit",
			varies = {
				-- { id = 95669, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94513, suffix = "N",		ilvl = 522, },
				{ id = 96041, suffix = "TF",	ilvl = 528, },
				{ id = 96413, suffix = "H",		ilvl = 535, },
				{ id = 96785, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "九头蛇之息",	token = "Breath of the Hydra",	constantStat = "haste",
			varies = {
				-- { id = 95711, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94521, suffix = "N",		ilvl = 522, },
				{ id = 96083, suffix = "TF",	ilvl = 528, },
				{ id = 96455, suffix = "H",		ilvl = 535, },
				{ id = 96827, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "张叶的辉煌精华",	token = "Cha-Ye's Essence of Brilliance",	constantStat = "crit",
			varies = {
				-- { id = 95772, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94531, suffix = "N",		ilvl = 522, },
				{ id = 96144, suffix = "TF",	ilvl = 528, },
				{ id = 96516, suffix = "H",		ilvl = 535, },
				{ id = 96888, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "雷神的精准之视",	token = "Unerring Vision of Lei Shen",
			varies = {
				-- { id = 95814, suffix = "LFR",	ilvl = 502, maxupgrade = 2, },
				{ id = 94524, suffix = "N",		ilvl = 522, },
				{ id = 96186, suffix = "TF",	ilvl = 528, },
				{ id = 96558, suffix = "H",		ilvl = 535, },
				{ id = 96930, suffix = "HTF",	ilvl = 541, },
			},
		},
		{ name = "影踪突袭营的爆裂护符",	token = "Volatile Talisman of the Shado-Pan Assault",
			varies = {
				{ id = 94510, suffix = "",		ilvl = 522, maxupgrade = 2, },
			},
		},
	},
}

local func = loadfile([[..\lib_simc_lua.lua]])
if func then
	print("Loading library ...")
	func()
end

------------------------------------------------------------------------------

session = {
	-- header = header,
	profiles = {},
	min_ilvl = 522,
}

session.name, session.iterations = ...

if not session.name then
	for index, value in ipairs( base_profiles ) do
		print(index, value)
	end
	print("Session name:")
	io.stdin:flush()
	session.name = io.stdin:read("*l") or "DefaultSession"
end

if tonumber(session.name) then
	session.baseChar, session.mainStat, session.bestStat = unpack(base_profiles[tonumber(session.name)])
	session.name = session.baseChar
	print("Using base profile", session.baseChar)
else
	print("Base profile:")
	io.stdin:flush()
	session.baseChar = io.stdin:read("*l")
end

local func = loadfile([[Sessions\]] .. session.name .. [[.lua]])
if func then
	log("Loading session from file ...")
	func()
end

session.log_file = io.open([[Sessions\]] .. session.name .. [[.log]], "a+")
log("=== Starting process for %s ===", session.name)

if not session.iterations then
	print("Please specify iterations:")
	io.stdin:flush()
	session.iterations = math.max(math.ceil(io.stdin:read("*n") or 1), 1)
end

if session.bestStat == nil then
	print("Please specify best stat, 'none' for no reforging:")
	io.stdin:flush()
	session.bestStat = io.stdin:read("*l")
	if session.bestStat == "none" then
		session.bestStat = false
	end
end

if #session.profiles == 0 then
	log( "Generating profile list for base character", session.baseChar )
	table.insert(session.profiles, { profile = "iterations=" .. session.iterations * 10, name = "NoTrinket", })

	generate_profiles(Trinkets[session.mainStat])
end

session.header = header

save_session()

log("Processing profiles ...")
for index, profile in ipairs(session.profiles) do
	if profile.name == "萦雾之恐" then
		table.remove(session.profiles, index)
		log("Deleted trinket from session %s", session.name)
		os.execute("pause")
	end
end
for index, profile in ipairs(session.profiles) do
	local elapsed, simcElapsed = process_profile(profile, index)
	local estimatedTotal = elapsed * (#session.profiles - index)
	if elapsed > 0 then
		log("Sim #%d took time %.3f / %.3f (%.2f%%), %d sec left.", index, simcElapsed, elapsed, simcElapsed / elapsed * 100, estimatedTotal)
	end
end

save_session()

log("Calculating rating ...")
session.trinketList = {}
session.trinketListReverse = {}
session.ilvlList = {}
session.ilvlListReverse = {}

local baseProfile = find_item(session.profiles, "name", "NoTrinket")
local baseDPS = baseProfile.dps
local baseErr = baseProfile.err
for index = 2, #session.profiles do
	local profile = session.profiles[index]
	session.trinketList[profile.name] = profile.base_ilvl
	session.ilvlList[profile.ilvl] = true

	profile.rating = profile.dps - baseDPS
	session.maxErr = math.max(baseErr + profile.err, session.maxErr or 0)
end

-- Make a list of ilevel
for ilvl in pairs( session.ilvlList ) do
	table.insert( session.ilvlListReverse, ilvl )
end
-- Sort it from high to low
table.sort(session.ilvlListReverse,
	function ( lvl1, lvl2 )
		return lvl1 > lvl2
	end
)

-- Make a list of trinket
for name in pairs( session.trinketList ) do
	table.insert( session.trinketListReverse, name )
end
-- Sort trinket list by their normal item level, and name
table.sort(session.trinketListReverse,
	function ( name1, name2 )
		return session.trinketList[name1] > session.trinketList[name2] or
				( session.trinketList[name1] == session.trinketList[name2] and name1 > name2)
	end
)

log("Writing output files ...")
local bbcode = io.open([[Sessions\]] .. session.name .. [[.bbcode]], "w")
local csv = io.open([[Sessions\]] .. session.name .. [[.csv]], "w")
local js = io.open([[Sessions\]] .. session.name .. [[.js]], "w")
bbcode:write("Profile: ", session.name, "\n")
bbcode:write("[table]", "\n")

-- Header of table - name of trinkets
log("Writing headers of output ...")
js:write([[
	function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
]])
bbcode:write("[tr]", "\n")
bbcode:write("[td]", "[/td]", "\n")
-- csv:write("\t")
js:write("[", "'x'")

for index, name in pairs( session.trinketListReverse ) do
	bbcode:write("[td]", find_item(session.profiles, "name", name).bbcode, "[/td]", "\n")
	csv:write("\t", name)
	-- js:write(",\t(\"", name, "\").getBytes(\"UTF-8\")")
	js:write(",\t\"", encode_java_str(name), "\"")
	-- js:write(",\t\"", name, "\"")
	-- js:write(",\t\"trinket", index, "\"")
end
bbcode:write("[/tr]", "\n")
csv:write("\n")
js:write("]")

for index, ilvl in pairs( session.ilvlListReverse ) do
	-- Leading col of line: ilvl in bold
	bbcode:write("[tr]")
	bbcode:write("[td]", "[b]", ilvl, "[/b]", "[/td]")
	csv:write(ilvl)
	js:write(",", "\n", "[", ilvl)

	for index, name in pairs( session.trinketListReverse ) do
		bbcode:write("[td]")
		js:write(",", "\t")
		csv:write("\t")
		local profileOrig = find_item(session.profiles, function (profile)
			return profile.name == name and profile.ilvl == ilvl and not profile.reforgeAll
		end)
		local profileFull = find_item(session.profiles, function (profile)
			return profile.name == name and profile.ilvl == ilvl and profile.reforgeAll
		end)
		if profileOrig then
			if profileFull then
				bbcode:write(math.floor(profileFull.rating))
				bbcode:write(" (", math.floor(profileOrig.rating), ")")
				csv:write(profileFull.rating)
				js:write(profileFull.rating)
			else
				bbcode:write(math.floor(profileOrig.rating))
				csv:write(profileOrig.rating)
				js:write(profileOrig.rating)
			end
		else
			js:write("null")
		end
		bbcode:write("[/td]")
		-- js:write("\t")
	end
	bbcode:write("[/tr]", "\n")
	csv:write("\n")
	js:write("]")
end
bbcode:write("[/table]", "\n")
bbcode:write("表中所有评分误差不高于", session.maxErr, "。", "\n")
local revision, last_changed_date = get_simc_version()
bbcode:write("基于SimC版本 r", revision, "，子版本最后更改日期 ", last_changed_date, "。", "\n")
bbcode:close()
csv:close()
js:write("\n")
js:write([[
	  ]);

  // Create and draw the visualization.
  new google.visualization.LineChart(document.getElementById('visualization')).
      draw(data, {curveType: "function",
                  width: 500, height: 400,
                  vAxis: {maxValue: 10},
                  pointSize: 5,
                  lineWidth: 2,
                  interpolateNulls: true
                 }
          );
}
​]])
js:close()

log("===Process finished===")
if session.log_file then
	session.log_file:close()
end
